package com.fenrirtec.aepp.common.api;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.common.condition.TenderCondition;
import com.fenrirtec.aepp.common.dto.TenderInformationDto;
import com.fenrirtec.aepp.common.service.InformationService;
import com.fenrirtec.aepp.common.service.impl.InformationServiceImpl;
import com.fenrirtec.aepp.common.support.JSONActionSupport;
import com.fenrirtec.core.definition.BaseDefinition.API;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;
import com.fenrirtec.core.utils.JsonUtils;

public class InformationSearchAPI extends JSONActionSupport{
	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(InformationSearchAPI.class);
	
	public InformationSearchAPI() {
		
	}
	
	private String param;
	
	private int _page;
	
	private int _rows;

	public String getParam() {
		return this.param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	public int getPage() {
		return _page;
	}

	public void setPage(int page) {
		this._page = page;
	}

	public int getRows() {
		return _rows;
	}

	public void setRows(int rows) {
		this._rows = rows;
	}

	@Override
	protected List<ErrorInfo> doValidate() {
		return null;
	}

	@Override
	protected JSONObject doExecute() {
		// 
		InformationService service = new InformationServiceImpl();
		List<TenderInformationDto> tenderInformationDtoList = null;
		Integer tenderCount = 0;
		
		try {
			JSONObject jsonObj = JSONObject.parseObject(this.param);
			TenderCondition condition = new TenderCondition();
			
			if (jsonObj != null && !jsonObj.isEmpty()) {
				condition = JsonUtils.toBean(jsonObj, TenderCondition.class);
			}

			condition.setPage(_page);
			condition.setRows(_rows);
			
			tenderCount = service.countByCnd(condition);
			tenderInformationDtoList = service.searchByCnd(condition);
			
		} catch (DatabaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("database error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (UnexpectedException e) {
			if (logger.isErrorEnabled()) {
				logger.error("unexpected error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		}
		
		JSONObject root = new JSONObject();
		root.put("total", tenderCount);
		if (tenderInformationDtoList != null && tenderInformationDtoList.size() > 0) {
			root.put("tenders", JsonUtils.fromBean(tenderInformationDtoList));
		}
		return root;
	}
}
